<template>
  <div class="content-area">
    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">患者姓名</div>
          <el-input
            v-model="filters.patientName"
            placeholder="请输入患者姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">病历编号</div>
          <el-input
            v-model="filters.recordId"
            placeholder="请输入病历编号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">就诊日期</div>
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">主治医生</div>
          <el-select
            v-model="filters.doctor"
            placeholder="请选择医生"
            clearable
          >
            <el-option label="张医生" value="张医生" />
            <el-option label="李医生" value="李医生" />
            <el-option label="王医生" value="王医生" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">病历状态</div>
          <el-select
            v-model="filters.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="初诊" value="initial" />
            <el-option label="复诊" value="followup" />
            <el-option label="已完成" value="completed" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchRecords">查询</el-button>
        <el-button type="success" @click="showAddRecordDialog">
          <el-icon><Plus /></el-icon>
          新建病历
        </el-button>
      </div>
    </div>

    <!-- 病历表格 -->
    <div class="record-table">
      <div class="table-header">
        <div class="table-title">病历列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Document /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table
        :data="pagedRecords"
        style="width: 100%"
        stripe
        border
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="recordId" label="病历编号" width="120" fixed />
        <el-table-column label="患者信息" min-width="180">
          <template #default="{ row }">
            <div class="patient-info">
              <div class="patient-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div>
                <div class="patient-name">{{ row.patientName }}</div>
                <div class="patient-meta">
                  {{ row.patientGender }} · {{ row.patientAge }}岁
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="visitDate"
          label="就诊日期"
          width="120"
          sortable
        />
        <el-table-column prop="department" label="科室" width="120" />
        <el-table-column prop="doctor" label="主治医生" width="120" />
        <el-table-column
          prop="diagnosis"
          label="初步诊断"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewRecordDetails(row)"
                >详情</el-button
              >
              <el-button size="small" type="primary" @click="editRecord(row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定要删除这条病历记录吗？"
                @confirm="deleteRecord(row)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredRecords.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 病历详情/编辑对话框 -->
  <el-dialog
    v-model="recordDialog.visible"
    :title="recordDialog.isEdit ? '编辑病历' : '病历详情'"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      :model="recordForm"
      label-width="100px"
      :rules="recordRules"
      ref="recordFormRef"
    >
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <div class="form-row">
          <el-form-item label="患者姓名" prop="patientName">
            <el-input
              v-model="recordForm.patientName"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
          <el-form-item label="病历编号" prop="recordId">
            <el-input v-model="recordForm.recordId" :disabled="true" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="性别" prop="patientGender">
            <el-input
              v-model="recordForm.patientGender"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
          <el-form-item label="年龄" prop="patientAge">
            <el-input
              v-model="recordForm.patientAge"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
        </div>
      </div>

      <div class="form-section">
        <div class="section-title">就诊信息</div>
        <div class="form-row">
          <el-form-item label="就诊日期" prop="visitDate">
            <el-date-picker
              v-model="recordForm.visitDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
          <el-form-item label="科室" prop="department">
            <el-input
              v-model="recordForm.department"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="主治医生" prop="doctor">
            <el-input
              v-model="recordForm.department"
              :disabled="!recordDialog.isEdit"
            />
          </el-form-item>
          <el-form-item label="病历状态" prop="status">
            <el-select
              v-model="recordForm.status"
              :disabled="!recordDialog.isEdit"
            >
              <el-option label="初诊" value="initial" />
              <el-option label="复诊" value="followup" />
              <el-option label="已完成" value="completed" />
              <el-option label="已归档" value="archived" />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <div class="form-section">
        <div class="section-title">诊断信息</div>
        <el-form-item label="主诉" prop="chiefComplaint">
          <el-input
            v-model="recordForm.chiefComplaint"
            type="textarea"
            :rows="2"
            placeholder="请输入患者主诉"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="现病史" prop="presentIllness">
          <el-input
            v-model="recordForm.presentIllness"
            type="textarea"
            :rows="3"
            placeholder="请输入现病史"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="既往史" prop="pastHistory">
          <el-input
            v-model="recordForm.pastHistory"
            type="textarea"
            :rows="2"
            placeholder="请输入既往史"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="过敏史" prop="allergyHistory">
          <el-input
            v-model="recordForm.allergyHistory"
            type="textarea"
            :rows="2"
            placeholder="请输入过敏史"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="体格检查" prop="physicalExam">
          <el-input
            v-model="recordForm.physicalExam"
            type="textarea"
            :rows="3"
            placeholder="请输入体格检查结果"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="初步诊断" prop="diagnosis">
          <el-input
            v-model="recordForm.diagnosis"
            type="textarea"
            :rows="2"
            placeholder="请输入初步诊断"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="处理意见" prop="treatmentPlan">
          <el-input
            v-model="recordForm.treatmentPlan"
            type="textarea"
            :rows="3"
            placeholder="请输入处理意见"
            :disabled="!recordDialog.isEdit"
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="recordDialog.visible = false">关闭</el-button>
      <el-button
        type="primary"
        v-if="recordDialog.isEdit"
        @click="submitRecordForm"
      >
        保存
      </el-button>
      <el-button type="primary" v-else @click="startEditRecord">
        编辑
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import SiderLift from "@/components/doctor/SiderLift.vue";
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";



const sidebarOpen = ref(false);
const loading = ref(false);
const filters = reactive({
  patientName: "",
  recordId: "",
  dateRange: [],
  doctor: "",
  status: "",
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pagetotal: 0,
});

// 病历数据
const records = ref([]);

// 病历对话框相关
const recordDialog = reactive({
  visible: false,
  isEdit: false,
});

const recordForm = reactive({
  id: "",
  recordId: "",
  patientId: "",
  patientName: "",
  patientGender: "",
  patientAge: "",
  visitDate: "",
  department: "心血管内科",
  doctor: "张医生",
  chiefComplaint: "",
  presentIllness: "",
  pastHistory: "",
  allergyHistory: "",
  physicalExam: "",
  diagnosis: "",
  treatmentPlan: "",
  status: "initial",
});

const recordRules = {
  patientName: [{ required: true, message: "请输入患者姓名", trigger: "blur" }],
  visitDate: [{ required: true, message: "请选择就诊日期", trigger: "change" }],
  department: [{ required: true, message: "请输入科室", trigger: "blur" }],
  doctor: [{ required: true, message: "请输入主治医生", trigger: "blur" }],
  chiefComplaint: [{ required: true, message: "请输入主诉", trigger: "blur" }],
  diagnosis: [{ required: true, message: "请输入初步诊断", trigger: "blur" }],
};

const recordFormRef = ref(null);

// 状态映射
const statusMap = {
  initial: "初诊",
  followup: "复诊",
  completed: "已完成",
  archived: "已归档",
};

const statusTagTypes = {
  initial: "primary",
  followup: "warning",
  completed: "success",
  archived: "info",
};

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

const getStatusText = (status) => {
  return statusMap[status] || status;
};

const getStatusTagType = (status) => {
  return statusTagTypes[status] || "";
};

const resetFilters = () => {
  filters.patientName = "";
  filters.recordId = "";
  filters.dateRange = [];
  filters.doctor = "";
  filters.status = "";
  loadRecords();
};

const searchRecords = () => {
  pagination.currentPage = 1;
  loadRecords();
};

// 计算属性 - 筛选后的病历
const filteredRecords = computed(() => {
  let result = [...records.value];

  // 按患者姓名筛选
  if (filters.patientName) {
    result = result.filter((item) =>
      item.patientName.includes(filters.patientName)
    );
  }

  // 按病历编号筛选
  if (filters.recordId) {
    result = result.filter((item) => item.recordId.includes(filters.recordId));
  }

  // 按医生筛选
  if (filters.doctor) {
    result = result.filter((item) => item.doctor === filters.doctor);
  }

  // 按状态筛选
  if (filters.status) {
    result = result.filter((item) => item.status === filters.status);
  }

  // 按日期范围筛选
  if (filters.dateRange && filters.dateRange.length === 2) {
    const [start, end] = filters.dateRange;
    result = result.filter((item) => {
      const date = item.visitDate;
      return date >= start && date <= end;
    });
  }

  return result;
});

// 计算属性 - 分页数据
const pagedRecords = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredRecords.value.slice(start, end);
});

const loadRecords = async () => {
  loading.value = true;

  try {
    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 模拟数据
    const mockData = [
      {
        id: "MR20230001",
        recordId: "MR20230001",
        patientId: "PT20230001",
        patientName: "张先生",
        patientGender: "男",
        patientAge: 45,
        visitDate: "2023-12-15",
        department: "心血管内科",
        doctor: "张医生",
        chiefComplaint: "胸闷、心悸3天",
        presentIllness:
          "患者3天前无明显诱因出现胸闷、心悸，活动后加重，休息可缓解",
        pastHistory: "高血压病史5年，规律服药",
        allergyHistory: "青霉素过敏",
        physicalExam: "BP 140/90mmHg，HR 88次/分，律齐，未闻及杂音",
        diagnosis: "1.冠心病？2.高血压2级",
        treatmentPlan:
          "1.完善心电图、心脏彩超检查\n2.给予硝酸甘油片备用\n3.低盐低脂饮食",
        status: "initial",
      },
      {
        id: "MR20230002",
        recordId: "MR20230002",
        patientId: "PT20230002",
        patientName: "王女士",
        patientGender: "女",
        patientAge: 32,
        visitDate: "2023-12-16",
        department: "心血管内科",
        doctor: "李医生",
        chiefComplaint: "头晕、乏力1周",
        presentIllness: "患者1周前开始出现头晕、乏力，无头痛、恶心呕吐",
        pastHistory: "体健",
        allergyHistory: "无",
        physicalExam: "BP 90/60mmHg，HR 76次/分，心肺听诊无异常",
        diagnosis: "低血压",
        treatmentPlan: "1.建议增加盐分摄入\n2.适量运动\n3.定期监测血压",
        status: "completed",
      },
      {
        id: "MR20230003",
        recordId: "MR20230003",
        patientId: "PT20230003",
        patientName: "李先生",
        patientGender: "男",
        patientAge: 58,
        visitDate: "2023-12-17",
        department: "心血管内科",
        doctor: "王医生",
        chiefComplaint: "反复胸痛1月",
        presentIllness: "患者1月来反复出现胸痛，持续数分钟，休息可缓解",
        pastHistory: "糖尿病史10年",
        allergyHistory: "无",
        physicalExam: "BP 130/80mmHg，HR 72次/分，心肺听诊无异常",
        diagnosis: "1.冠心病 心绞痛\n2.2型糖尿病",
        treatmentPlan:
          "1.完善冠脉CTA检查\n2.给予阿司匹林、硝酸酯类药物治疗\n3.控制血糖",
        status: "followup",
      },
      {
        id: "MR20230004",
        recordId: "MR20230004",
        patientId: "PT20230004",
        patientName: "赵女士",
        patientGender: "女",
        patientAge: 29,
        visitDate: "2023-12-18",
        department: "心血管内科",
        doctor: "张医生",
        chiefComplaint: "体检发现心律不齐",
        presentIllness: "体检时发现心律不齐，无明显不适",
        pastHistory: "体健",
        allergyHistory: "无",
        physicalExam: "BP 110/70mmHg，HR 78次/分，心律不齐",
        diagnosis: "心律失常 房性早搏",
        treatmentPlan: "1.24小时动态心电图检查\n2.避免咖啡、浓茶\n3.定期复查",
        status: "completed",
      },
      {
        id: "MR20230005",
        recordId: "MR20230005",
        patientId: "PT20230005",
        patientName: "刘先生",
        patientGender: "男",
        patientAge: 50,
        visitDate: "2023-12-19",
        department: "心血管内科",
        doctor: "李医生",
        chiefComplaint: "活动后气促2周",
        presentIllness: "患者2周来出现活动后气促，爬3层楼即感明显",
        pastHistory: "吸烟20年，10支/日",
        allergyHistory: "无",
        physicalExam: "BP 120/80mmHg，HR 82次/分，双肺底可闻及湿啰音",
        diagnosis: "1.慢性心功能不全\n2.慢性阻塞性肺疾病？",
        treatmentPlan: "1.完善心脏彩超、肺功能检查\n2.戒烟\n3.利尿剂治疗",
        status: "initial",
      },
    ];

    records.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载病历数据失败");
    console.error("加载病历数据失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
};

const viewRecordDetails = (record) => {
  Object.assign(recordForm, record);
  recordDialog.isEdit = false;
  recordDialog.visible = true;
};

const startEditRecord = () => {
  recordDialog.isEdit = true;
};

const editRecord = (record) => {
  Object.assign(recordForm, record);
  recordDialog.isEdit = true;
  recordDialog.visible = true;
};

const deleteRecord = (record) => {
  // 模拟删除操作
  records.value = records.value.filter((r) => r.id !== record.id);
  ElMessage.success("删除成功");
};

const showAddRecordDialog = () => {
  // 重置表单
  Object.assign(recordForm, {
    id: "",
    recordId: `MR202300${records.value.length + 1}`,
    patientId: "",
    patientName: "",
    patientGender: "",
    patientAge: "",
    visitDate: "",
    department: "心血管内科",
    doctor: "张医生",
    chiefComplaint: "",
    presentIllness: "",
    pastHistory: "",
    allergyHistory: "",
    physicalExam: "",
    diagnosis: "",
    treatmentPlan: "",
    status: "initial",
  });
  recordDialog.isEdit = true;
  recordDialog.visible = true;
};

const submitRecordForm = async () => {
  try {
    await recordFormRef.value.validate();

    // 模拟保存操作
    if (recordDialog.isEdit) {
      // 更新病历
      const index = records.value.findIndex((r) => r.id === recordForm.id);
      if (index !== -1) {
        records.value[index] = { ...recordForm };
      } else {
        // 新增病历
        const newRecord = { ...recordForm, id: recordForm.recordId };
        records.value.unshift(newRecord);
      }
      ElMessage.success("保存成功");
    }

    recordDialog.visible = false;
    loadRecords();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const exportData = () => {
  ElMessage.success("数据导出成功");
};

const refreshData = () => {
  loadRecords();
  ElMessage.success("数据已刷新");
};

onMounted(() => {
  loadRecords();
});
</script>

<style lang="scss" scoped>
.medical-record-container {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 继承预约管理页面的侧边栏和主内容区域样式 */

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.top-header {
  background: white;
  padding: 0 24px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.action-item {
  margin-left: 20px;
  cursor: pointer;
  position: relative;
}

.badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

/* 病历管理特定样式 */
.filter-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.record-table {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.patient-info {
  display: flex;
  align-items: center;
}

.patient-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #1a75bc;
}

.patient-name {
  font-weight: 500;
}

.patient-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

/* 病历表单样式 */
.form-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1a75bc;
}

.form-row {
  display: flex;
  gap: 16px;

  .el-form-item {
    flex: 1;
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .brand-text,
  .nav-text,
  .user-info {
    display: none;
  }

  .hospital-brand {
    justify-content: center;
    padding: 15px 0;
  }

  .nav-item {
    justify-content: center;
    padding: 16px 0;
  }

  .nav-icon {
    margin-right: 0;
  }

  .user-profile {
    justify-content: center;
  }

  .filter-item {
    min-width: 150px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: -80px;
    height: 100%;
    z-index: 1000;
    transition: left 0.3s;
  }

  .sidebar.open {
    left: 0;
  }

  .menu-toggle {
    display: block !important;
  }

  .filter-row {
    flex-direction: column;
  }

  .filter-item {
    width: 100%;
  }

  .action-buttons-cell {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-row {
    flex-direction: column;
    gap: 0;
  }
}

.menu-toggle {
  display: none;
  margin-right: 15px;
  cursor: pointer;
}
</style>